<template>
  <div>
    <el-dialog :close-on-click-modal="false" :before-close="handleBeforeClose"
    :visible=true :title="title" width="70%">

    <el-form ref="form" :model="form" :rules="rules" label-width="100px" label-position="right">

      <el-table :data="tableData">
        <el-table-column prop="parameter" label="生理参数" />
        <el-table-column prop="xlq" label="训练前">
          <template #default="scope">
            <el-input type="number"v-model="scope.row.xlq" />
          </template>
        </el-table-column>
        <el-table-column label="4.0-6.0kPa">
          <el-table-column prop="xl461"label="1min" width="120">
            <template #default="scope">
              <el-input type="number"v-model="scope.row.xl461" />
            </template>
          </el-table-column>
          <el-table-column prop="xl462" label="2min" width="120">
            <template #default="scope">
              <el-input type="number" v-model="scope.row.xl462" />
            </template>
          </el-table-column>
          <el-table-column prop="xl463" label="3min" width="120">
              <template #default="scope">
              <el-input
                type="number" v-model="scope.row.xl463" />
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column prop="xl46Xyh" label="卸压后3-5分钟">
          <template #default="scope">
            <el-input type="number" v-model="scope.row.xl46Xyh" />
          </template>
        </el-table-column>
        <el-table-column prop="xl68" label="6.0-8.0kPa">
          <template #default="scope">
            <el-input type="number" v-model="scope.row.xl68" />
          </template>
        </el-table-column>
        <el-table-column prop="xl68Xyh" label="卸压后3-5分钟">
          <template #default="scope">
            <el-input type="number" v-model="scope.row.xl68Xyh" />
          </template>
        </el-table-column>
        <el-table-column prop="xl810" label="8.0-10.0kPa">
          <template #default="scope">
            <el-input type="number" v-model="scope.row.xl810" />
          </template>
        </el-table-column>
        <el-table-column prop="xl810Xyh" label="卸压后">
          <template #default="scope">
            <el-input type="number" v-model="scope.row.xl810Xyh" />
          </template>
        </el-table-column>
      </el-table>
      <el-form-item label="主观症状">
        <el-select
          v-model="selectedFeels"
          placeholder="请选择"
          multiple
          filterable
          clearable
          style="width: 100%;"
        >
          <el-option
            v-for="feel in feelList"
            :key="feel.name"
            :label="feel.name"
            :value="feel.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="其他症状">
        <el-input type="textarea" v-model="otherFeel" />
      </el-form-item>

      <el-form-item label="书写表现">
        <el-input type="textarea" v-model="form.sxbx" />
      </el-form-item>

      <el-form-item label="医师建议">
        <el-input type="textarea" v-model="form.jy"/>
      </el-form-item>

      <el-row>
        <el-col :span="6" >
          <el-form-item label="结果判定">
            <el-select
              v-model="form.result"
              placeholder="请选择">
              <el-option
                v-for="[key, value] in resultOptions"
                :key="value"
                :label="value"
                :value="key"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" >
          <el-form-item label="记录人" prop="createBy">
            <el-input v-model="form.createBy" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="记录日期" prop="createTime">
            <el-date-picker v-model="form.createTime" :picker-options="pickerOptions" type="date" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="toggleExportDailog">导出预览</el-button>
        <el-button type="text" @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleCommit" :disabled="disabled">确认</el-button>
      </div>
  </el-dialog>
  <PrintDialog v-if="exportShow" @close="toggleExportDailog" :printData="form" :pilot="pilot"/> 
  </div>

</template>

<script>
import {get, edit, add} from '@/api/trainDmjyhx'
import feelMixin from '@/mixins/feelMixin'
import PrintDialog from './printDialog.vue'

import { RATE_RESULTS} from '@/utils/constants'

const defaultForm = { id: null, trainId: null, trainItemId: null, xlq: null, xl461: null, xl462: null, xl463: null, xl46Xyh: null, xl68: null, xl68Xyh: null, xl810: null, xl810Xyh: null, feels: null, result: null, jy: null}

export default {
  name: 'DmjyhxDialog',
  components: {
    PrintDialog
  },
  mixins: [feelMixin],
  props: {
    trainId: {
      type: Number,
      default: -1,
      required: true
    },
    itemId: {
      type: Number,
      default: -1,
      required: true
    },
    pilot: {
      type: Object,
      default: null
    }
  },
  computed: {
    disabled() {
      return this.form.id != null && !this.checkPer(['admin']);
    }
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }]
      },
      tableData: [
        { parameter: '心率（次/分）', xlq: null, xl461: null, xl462: null, xl463: null , xl46Xyh: null, xl68: null, xl68Xyh: null, xl810: null, xl810Xyh: null},
        { parameter: '呼吸（次/分）', xlq: null, xl461: null, xl462: null, xl463: null , xl46Xyh: null, xl68: null, xl68Xyh: null, xl810: null, xl810Xyh: null,},
        { parameter: '血压（mmHg）', xlq: null, xl461: null, xl462: null, xl463: null , xl46Xyh: null, xl68: null, xl68Xyh: null, xl810: null, xl810Xyh: null,},
      ],
      labelPosition: 'top',
      form: { ...defaultForm },
      title: '地面加压呼吸',
      rules: {
        // createBy: [{ required: true, message: '记录人不能为空', trigger: 'blur' }],
        // date: [{ required: true, message: '记录日期不能为空', trigger: 'blur' }]
      },
      resultOptions: RATE_RESULTS,
      exportShow: false,
      isLoading: false, // 提交按钮的加载状态
      selectedFeels: [],
      otherFeel: ''
    };
  },
  methods: {
    toggleExportDailog() {
      this.exportShow = !this.exportShow;
    },
    handleBeforeClose(done) {
      this.$emit('close', this.itemId);
      if (done) {
        done(); // 调用done()来关闭对话框        
      }
    },
    handleCommit() {
      // 使用 mixin 的方法构建感受字符串
      this.form.feels = this.buildFeelsString(this.selectedFeels, this.otherFeel)
      
      const xlData = this.tableData.reduce((acc, cur) => {
        acc.xlq = (acc.xlq ? acc.xlq + '|' : '') + cur.xlq;
        acc.xl461 = (acc.xl461 ? acc.xl461 + '|' : '') + cur.xl461;
        acc.xl462 = (acc.xl462 ? acc.xl462 + '|' : '') + cur.xl462;
        acc.xl463 = (acc.xl463 ? acc.xl463 + '|' : '') + cur.xl463;
        acc.xl46Xyh = (acc.xl46Xyh ? acc.xl46Xyh + '|' : '') + cur.xl46Xyh;
        acc.xl68 = (acc.xl68 ? acc.xl68 + '|' : '') + cur.xl68;
        acc.xl68Xyh = (acc.xl68Xyh ? acc.xl68Xyh + '|' : '') + cur.xl68Xyh;
        acc.xl810 = (acc.xl810 ? acc.xl810 + '|' : '') + cur.xl810;
        acc.xl810Xyh = (acc.xl810Xyh ? acc.xl810Xyh + '|' : '') + cur.xl810Xyh;
        return acc;
      }, {})

      Object.keys(xlData).forEach(key => {
        this.form[key] = xlData[key];
      });

      this.$refs['form'].validate(valid => {
        if (valid) {
          this.isLoading = true; // 提交按钮的加载状态
          this.form.trainId = this.trainId;
          this.form.trainItemId = this.itemId;
          if (this.form.id == null) {
            add(this.form).then(() => {
              this.$emit('close', this.itemId);
              this.isLoading = false;
            }).catch(() => {
              this.isLoading = false;
            });
          } else {
            edit(this.form).then(() => {
              this.$emit('close', this.itemId);
              this.isLoading = false;
            }).catch(() => {
              this.isLoading = false;
            });
          }
        }
      })
    },
    handleCancel() {
      this.$emit('cancel', this.itemId);
    }
  },
  async created() {
    if (this.trainId !== -1) {
      // 使用 mixin 的方法确保感受列表已加载
      await this.initFeelData()
      
      get(this.trainId, this.itemId).then(response => {
        this.form = Object.assign(this.form, response);
        
        // 使用 mixin 的方法解析感受字符串
        const { selectedIds, otherFeel } = this.parseFeelsString(this.form.feels)
        this.selectedFeels = selectedIds
        this.otherFeel = otherFeel

        const xlq = this.form.xlq.split('|');
        const xl461 = this.form.xl461.split('|');
        const xl462 = this.form.xl462.split('|');
        const xl463 = this.form.xl463.split('|');
        const xl46Xyh = this.form.xl46Xyh.split('|');
        const xl68 = this.form.xl68.split('|');
        const xl68Xyh = this.form.xl68Xyh.split('|');
        const xl810 = this.form.xl810.split('|');
        const xl810Xyh = this.form.xl810Xyh.split('|');
        this.tableData.map((item, index) => {
          item.xlq = xlq[index];
          item.xl461 = xl461[index];
          item.xl462 = xl462[index];
          item.xl463 = xl463[index];
          item.xl46Xyh = xl46Xyh[index];
          item.xl68 = xl68[index];
          item.xl68Xyh = xl68Xyh[index];
          item.xl810 = xl810[index];
          item.xl810Xyh = xl810Xyh[index];
        })
        console.log(response, this.form);

      });
    }
  },
  updated() {

    // 组件更新后执行的逻辑，比如获取数据
  },
  mounted() {
    console.log("this.pilot", this.pilot);
  }
}
</script>

<style scoped>

::v-deep .el-input__inner {
  text-align: center;
  padding: 0;
}
::v-deep .el-table--small .el-table__cell {
  padding: 0;
}
.el-table {
  margin-bottom: 20px;
}
::v-deep .el-table .cell {
  padding: 0;
}

::v-deep .el-table th.el-table__cell>.cell {
  text-align: center;
}
</style>